package com.example.javafx.单选按钮;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * 单选按钮事件
 */
public class Main_1 extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        Scene scene = new Scene(new Group());
        primaryStage.setWidth(250);
        primaryStage.setHeight(150);

        final ToggleGroup group = new ToggleGroup();

        RadioButton rb1 = new RadioButton("A");
        rb1.setToggleGroup(group);
        rb1.setUserData("A");

        RadioButton rb2 = new RadioButton("B");
        rb2.setToggleGroup(group);
        rb2.setUserData("B");

        RadioButton rb3 = new RadioButton("C");
        rb3.setToggleGroup(group);
        rb3.setUserData("C");

        group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
            @Override
            public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) {
                if(group.getSelectedToggle()!=null){
                    System.out.println(group.getSelectedToggle().getUserData().toString());
                }
            }
        });

        HBox hBox = new HBox();
        VBox vBox = new VBox();
        vBox.getChildren().add(rb1);
        vBox.getChildren().add(rb2);
        vBox.getChildren().add(rb3);
        vBox.setSpacing(10);

        hBox.getChildren().add(vBox);
        hBox.setSpacing(10);
        hBox.setPadding(new Insets(20,10,10,20));

        ((Group)scene.getRoot()).getChildren().add(hBox);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}
